<template>
  <view class="cont_index">
    <u-navbar
      title="首页"
      :placeholder="true"
      :safeAreaInsetTop="true"
      bgColor="#f5f6f5"
    >
      <view
        class="u-nav-slot"
        slot="left"
      ></view>
    </u-navbar>
    <!-- <u-navbar title="首页" :placeholder="true" :safeAreaInsetTop="true" bgColor="#f5f6f5" titleStyle="color:#000" /> -->
    <view style="position: absolute; width: 100%; background-color: #f5f6f5">
      <view v-show="staff">
        <u-row
          justify="space-between"
          customStyle="margin: 10px 20rpx"
        >
          <u-col span="12">
            <!-- <cover-view> -->

            <!-- 	<view class="dateBox">
						<uni-datetime-picker v-model="range" rangeSeparator="至" type="daterange"
							@closeCanvas="closeCanvas" @showCanvas="showCanvas" @change="handleDateChangeRange" />
					</view> -->
            <view class="dateBox-hood">
              <view
                :class="{
                  'dateBox-yesterday': true,
                  'dateBox-button': clickButton === '0',
                }"
                @click="todayTime"
                >今天</view
              >
              <view
                :class="{
                  'dateBox-nearlySevenDays': true,
                  'dateBox-button': clickButton === '1',
                }"
                @click="yesterday"
                >昨天</view
              >
              <view
                :class="{
                  'dateBox-nearlySevenDays': true,
                  'dateBox-button': clickButton === '2',
                }"
                @click="nearlySevenDays"
                >近七天</view
              >
              <view
                :class="{
                  'dateBox-oneMonth': true,
                  'dateBox-button': clickButton === '3',
                }"
                @click="oneMonth"
                >近30天</view
              >
            </view>
          </u-col>
          <u-col span="2"> </u-col>
        </u-row>
      </view>

      <view class="data-overview">
        <!-- <view class="title">
					<text>数据概览</text>
				</view> -->
        <view class="data-box" :class="{height_375: data.isShowAmt != 1 }">
          <image
            class="data-img"
            :class="{height_375: data.isShowAmt != 1 }"
            src="../../static/index-img/组 46.png"
          />
          <view class="data-body">
            <view>
              <view class="type-text">营业总额(元)</view>
              <view class="num-type">￥{{ data.rechargeAndPayAmt || 0 }}</view>
            </view>
            <view class="data-item-bootn">
              <view class="flex_item">
                <view class="type-text">订单金额(元)</view>
                <view class="num">{{ data.refuelingAmt || 0 }}</view>
              </view>
              <view class="flex_item">
                <view class="type-text">充值金额(元)</view>
                <view class="num">{{ data.rechargeAmt || 0 }}</view>
              </view>
              <view class="flex_item">
                <view class="type-text">订单笔数(笔)</view>
                <view class="num">{{ data.orderAmt || 0 }}</view>
              </view>
              <view class="flex_item" v-if="data.isShowAmt == 1 ">
                <view class="type-text">实收金额(元)</view>
                <view class="num">{{ data.ssAmt || 0 }}</view>
              </view>
            </view>
          </view>
        </view>
      </view>
      <view
        class="charts-box"
        :class="[hiddenCanvas ? 'hiddle' : '']"
      >
        <view class="shouru">收入渠道分布</view>
        <view class="right_charts">
          <!-- <view class="quin_data">
						<qiun-data-charts v-show="!showDate" type="ring" :opts="ringOpts" :chartData="chartRingData" />
					</view> -->
          <view class="title_list">
            <view
              class="vard_item"
              @click="() => changValue(item)"
              v-for="(item, index) in data.payTypePercentage"
              :key="item.name"
            >
              <!-- <view class="icon" :class="[`icon${index}`]"></view> -->
              <!-- <view class="name">
								<view class="a">{{ item.name }}</view>
								<view class="val">
									<view class="b">{{ item.y }}</view><text class="c">%</text>
								</view>
							</view> -->
              <view class="name">{{ item.name }}</view>
              <view
                :class="{
                  paycount: true,
                  'paycount-0': index === 0,
                  'paycount-1': index === 1,
                  'paycount-2': index === 2,
                  'paycount-3': index === 3,
                  'paycount-4': index === 4,
                  'paycount-5': index === 5,
                  'paycount-6': index === 6,
                  'paycount-7': index === 7,
                }"
              >
                <span style="font-size: 35rpx">{{ item.paycount }}</span>
                <span
                  style="font-size: 20rpx; margin-left: 2px; margin-top: 5rpx"
                  >元</span
                >
              </view>
            </view>
          </view>
        </view>
      </view>
      <view
        class="charts-box"
        :class="[hiddenCanvas ? 'hiddle' : '']"
      >
        <view class="shouru">近7日交易趋势分析</view>
        <view class="shouru-title">
          <view style="margin-left: 15rpx">（元）</view>
          <view style="margin-right: 15rpx">（笔）</view>
        </view>
        <view class="charts_jiaoyi">
          <qiun-data-charts
            type="line"
            :opts="columnOpts"
            :chartData="chartColumnData"
          />
        </view>
      </view>
    </view>
  </view>
</template>
<script>
import {
  homeSumQuery,
  getInfo,
  employeePermission,
} from '@/common/yftx-api.js';
import { getYm, getDateArrNew } from '@/util/utils.js';
import store from '@/store';
// import navBar from "@/components/nav/nav.vue";
export default {
  // components: {
  // 	navBar,
  // },
  data() {
    return {
      clickButton: '0',
      range: ['2023-09-05', '2023-09-09'],
      data: {},
      startDate: '',
      endDate: '',
      dateKey: 1,
      showDate: false,
      hiddenCanvas: false,
      dateVal: '',
      chartRingData: {}, // 环形图
      ringOpts: {
        rotate: false,
        rotateLock: false,
        color: [
          '#00C889',
          '#0FA2FB',
          '#FF6B00',
          '#FF2F47',
          '#FFD400',
          '#12d9db',
          '#ccc',
        ],
        padding: [5, 5, 5, 5],
        dataLabel: false,
        enableScroll: false,
        legend: {
          show: false,
          position: 'right',
          lineHeight: 25,
        },

        title: {
          name: '',
          fontSize: 14,
          color: '#333741',
        },
        subtitle: {
          name: '',
          fontSize: 16,
          color: '#333741',
        },
        extra: {
          ring: {
            ringWidth: 60,
            activeOpacity: 0.5,
            activeRadius: 10,
            offsetAngle: 0,
            labelWidth: 15,
            border: false,
            borderWidth: 3,
            borderColor: '#FFFFFF',
          },
        },
      },
      chartColumnData: {}, //折线图
      columnOpts: {
        color: [
          '#355EF6',
          '#E95F86',
          '#FAC858',
          '#EE6666',
          '#73C0DE',
          '#3CA272',
          '#FC8452',
          '#9A60B4',
          '#ea7ccc',
        ],
        padding: [15, 15, 0, 5],
        dataLabel: false,
        dataPointShape: false,
        enableScroll: false,
        legend: {},
        xAxis: {
          disableGrid: true,
        },
        yAxis: {
          data: [
            {
              position: 'right',

              gridType: 'dash',
              dashLength: 2,
            },
            {
              position: 'left',

              gridType: 'dash',
              dashLength: 2,
            },
          ],
        },
        extra: {
          line: {
            type: 'curve',
            width: 2,
            activeType: 'hollow',
          },
        },
      },

      staff: null,

      top: 0,
    };
  },
  computed: {
    couponAmt() {
      const { ssAmt, refuelingAmt } = this.data;
      if (ssAmt && refuelingAmt) {
        return (Number(refuelingAmt) - Number(ssAmt)).toFixed(2);
      }
      return 0;
    },
  },
  onLoad() {
    this.clickButton = '0';
    uni.$on('closeCanvas', () => this.closeCanvas());
    uni.$on('showCanvas', () => this.showCanvas());
  },
  onShow() {
    this.clickButton = '0';
    this.getData();
  },
  watch: {},
  methods: {
    add(m) {
      return m < 10 ? '0' + m : m;
    },

    // 点击了今天
    todayTime() {
      this.clickButton = '0';
      let dateTime = [];
      const today = new Date();

      const yesterdays = new Date(today.setTime(today.getTime()));
      const ys = yesterdays.getFullYear();
      const ms = yesterdays.getMonth() + 1;
      const ds = yesterdays.getDate();
      const s = ys + '-' + this.add(ms) + '-' + this.add(ds) + ' ' + '00:00:00'; //开始

      const yesterday = new Date(today.setTime(today.getTime()));
      const y = yesterday.getFullYear();
      const m = yesterday.getMonth() + 1;
      const d = yesterday.getDate();
      const e = y + '-' + this.add(m) + '-' + this.add(d) + ' ' + '23:59:59'; //结束

      dateTime.push(s);
      dateTime.push(e);

      this.handleDateChangeRange(dateTime);
    },
    // 点击了昨天
    yesterday() {
      this.clickButton = '1';
      let dateTime = [];
      const today = new Date();

      const yesterdays = new Date(
        today.setTime(today.getTime() - 24 * 60 * 60 * 1000)
      );
      const ys = yesterdays.getFullYear();
      const ms = yesterdays.getMonth() + 1;
      const ds = yesterdays.getDate();
      const s = ys + '-' + this.add(ms) + '-' + this.add(ds) + ' ' + '00:00:00'; //开始

      const yesterday = new Date(
        today.setTime(today.getTime() + 0 * 24 * 60 * 60 * 1000)
      );
      const y = yesterday.getFullYear();
      const m = yesterday.getMonth() + 1;
      const d = yesterday.getDate();
      const e = y + '-' + this.add(m) + '-' + this.add(d) + ' ' + '23:59:59'; //结束

      dateTime.push(s);
      dateTime.push(e);

      this.handleDateChangeRange(dateTime);
    },
    // 点击近七天
    nearlySevenDays() {
      this.clickButton = '2';
      let dateTime = [];
      const today = new Date();

      const yesterdays = new Date(
        today.setTime(today.getTime() - 6 * 24 * 60 * 60 * 1000)
      );
      const ys = yesterdays.getFullYear();
      const ms = yesterdays.getMonth() + 1;
      const ds = yesterdays.getDate();
      const s = ys + '-' + this.add(ms) + '-' + this.add(ds) + ' ' + '00:00:00'; //开始

      const yesterday = new Date(
        today.setTime(today.getTime() + 6 * 24 * 60 * 60 * 1000)
      );
      const y = yesterday.getFullYear();
      const m = yesterday.getMonth() + 1;
      const d = yesterday.getDate();
      const e = y + '-' + this.add(m) + '-' + this.add(d) + ' ' + '23:59:59'; //结束

      dateTime.push(s);
      dateTime.push(e);

      this.handleDateChangeRange(dateTime);
    },
    // 点击近30天
    oneMonth() {
      this.clickButton = '3';
      let dateTime = [];
      const today = new Date();

      const yesterdays = new Date(
        today.setTime(today.getTime() - 29 * 24 * 60 * 60 * 1000)
      );
      const ys = yesterdays.getFullYear();
      const ms = yesterdays.getMonth() + 1;
      const ds = yesterdays.getDate();
      const s = ys + '-' + this.add(ms) + '-' + this.add(ds) + ' ' + '00:00:00'; //开始

      const yesterday = new Date(
        today.setTime(today.getTime() + 29 * 24 * 60 * 60 * 1000)
      );
      const y = yesterday.getFullYear();
      const m = yesterday.getMonth() + 1;
      const d = yesterday.getDate();
      const e = y + '-' + this.add(m) + '-' + this.add(d) + ' ' + '23:59:59'; //结束

      dateTime.push(s);
      dateTime.push(e);

      this.handleDateChangeRange(dateTime);
    },
    closeCanvas() {
      this.hiddenCanvas = true;
    },
    showCanvas() {
      this.hiddenCanvas = false;
    },
    changValue(val) {
      (this.ringOpts.title = {
        name: val.name,
        fontSize: 14,
        color: '#333741',
      }),
        (this.ringOpts.subtitle = {
          name: `${val.y}%`,
          fontSize: 10,
          color: '#333741',
        });
    },
    handleSwitch() {
      if (this.dateKey === 2) {
        return (this.dateKey = 1);
      }
      this.dateVal = getYm();
      this.dateKey++;
    },
    handleDateChangeRange(arr) {
      this.startDate = arr[0];
      this.endDate = arr[1];
      let data = {
        beginTime: arr[0],
        endTime: arr[1],
      };
      let userLevel = store.state.userLevel;
      if (['1', '2', '5', '6'].includes(userLevel)) {
        data.isDeleted = 0;
      }
      homeSumQuery(data).then((res) => {
        if (res && res.code === 200) {
          this.data = res.data;
          const a = res.data.payTypePercentage.find(
            (item) => item.name === '现金支付'
          );
          this.ringOpts.title = {
            name: a.name,
          };

          (this.ringOpts.subtitle = {
            name: `${a.y}%`,
            fontSize: 10,
            color: '#333741',
          }),
            this.getServerData(res.data.payTypePercentage, res.data.series);
        }
      });
    },
    async getData() {
      let data = {
        beginTime: this.range[2],
        endTime: this.range[3],
      };
      let res = await employeePermission();

      if (res.data.staff && res.data.employeeShow === '1') {
        this.staff = false;
      } else {
        this.staff = true;
      }

      this.range = getDateArrNew();
      this.startDate = this.range[2];
      this.endDate = this.range[3];
      data = {
        beginTime: this.range[0],
        endTime: this.range[1],
      };

      let userLevel = store.state.userLevel;
      if (['1', '2', '5', '6'].includes(userLevel)) {
        data.isDeleted = 0;
      }
      homeSumQuery(data).then((res) => {
        if (res && res.code === 200) {
          this.data = res.data;
          this.getServerData(res.data.payTypePercentage, res.data.series);
        }
      });
    },
    // 获取当前日期的前7天
    getDays() {
      //设置日期，当前日期的前七天
      let myDate = new Date(); //获取今天日期
      myDate.setDate(myDate.getDate() - 7);
      let dateArray = [];
      let dateTemp;
      let flag = 1;
      let month;
      let date;
      for (var i = 0; i < 7; i++) {
        month = myDate.getMonth() + 1;
        date = myDate.getDate();
        if (date < 10) date = `0${date}`;
        if (month < 10) month = `0${month}`;
        dateTemp = month + '-' + date;
        dateArray.push(dateTemp);
        myDate.setDate(myDate.getDate() + flag);
      }
      return dateArray;
    },
    getServerData(data, seriesCloumn) {
      //模拟从服务器获取数据时的延时
      setTimeout(() => {
        const series = data.map((item, index) => {
          return {
            name: `${item.name}`,
            value: item.y,
            labelText: `${item.name}${item.y}%,${item.paycount}元`,
            textColor: this.ringOpts.color[index],
          };
        });
        //模拟服务器返回数据，如果数据格式和标准格式不同，需自行按下面的格式拼接
        let ring = {
          series: [
            {
              data: series,
            },
          ],
        };
        this.chartRingData = JSON.parse(JSON.stringify(ring));
        const seriesC = seriesCloumn.map((item, index) => {
          return {
            index,
            name: item.name,
            data: item.data.map((item) => item.toFixed(0)),
          };
        });
        const newDate = this.getDays();
        let column = {
          categories: newDate,
          series: seriesC,
        };
        this.chartColumnData = JSON.parse(JSON.stringify(column));
      }, 500);
    },
    handleDateConfirm(e) {
      this.dateVal = this.result(e.value, e.mode);
      this.showDate = false;
    },
    handleShowDate() {
      this.showDate = true;
    },
    result(time, mode) {
      const timeFormat = uni.$u.timeFormat;
      switch (mode) {
        case 'datetime':
          return timeFormat(time, 'yyyy-mm-dd hh:MM');
        case 'date':
          return timeFormat(time, 'yyyy-mm-dd');
        case 'year-month':
          return timeFormat(time, 'yyyy-mm');
        case 'time':
          return time;
        default:
          return '';
      }
    },
    formatter(type, value) {
      if (type === 'year') {
        return `${value}年`;
      }
      if (type === 'month') {
        return `${value}月`;
      }
      return value;
    },
  },
  created() {
    this.clickButton = '0';
    const demo = uni.getMenuButtonBoundingClientRect();
    this.top = demo.top + demo.top + 'px';
  },
};
</script>
<style lang="scss" scoped>
.shouru-title {
  width: 100%;
  height: 60rpx;
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  font-size: 26rpx;
}

.dateBox-button {
  background-color: #e4e5e4 !important;
}

.paycount-0 {
  color: #64d3a6;
}

.paycount-1 {
  color: #355ef6;
}

.paycount-2 {
  color: #f1b23f;
}

.paycount-3 {
  color: #ff4445;
}

.paycount-4 {
  color: #ec5f8d;
}

.paycount-5 {
  color: #ec5f8d;
}

.paycount-6 {
  color: #ec5f8d;
}

.paycount-7 {
  color: #ec5f8d;
}

.type-text {
  font-size: 24rpx;
  font-family: PingFang SC;
  color: #fff;
  margin-bottom: 8px;
}

.num {
  font-family: PingFang SC;
  font-size: 35rpx;
  color: #fff;
  margin-left: 2px;
}

.num-type {
  font-family: PingFang SC;
  font-size: 55rpx;
  color: #fff;
  margin-bottom: 20rpx;
}

.dateBox-hood {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  height: 70rpx;
  text-align: center;
  margin: 5px 10px 0px 10px;
  color: #000;
  border: 2px solid #fff;
  border-radius: 35rpx;

  .dateBox-yesterday {
    border-bottom-left-radius: 35rpx;
    border-top-left-radius: 35rpx;
    width: 33%;
    height: 70rpx;
    line-height: 70rpx;
    background-color: #fff;
  }

  .dateBox-nearlySevenDays {
    width: 34%;
    height: 70rpx;
    line-height: 70rpx;
    background-color: #fff;
  }

  .dateBox-oneMonth {
    border-bottom-right-radius: 35rpx;
    border-top-right-radius: 35rpx;
    width: 33%;
    height: 70rpx;
    line-height: 70rpx;
    background-color: #fff;
  }
}

/deep/ .uni-date-x {
  color: rgba(255, 255, 255, 0.6) !important;
  background-color: transparent !important;
}

/deep/ .uni-date {
  background-color: rgba(255, 255, 255, 0.2) !important;
  border-radius: 40rpx !important;
  border: 1px solid rgba(255, 255, 255, 0.2) !important;
}

/deep/ .uni-date-x--border {
  border-radius: 40rpx !important;
  border: none !important;
}

.cont_index {
  background-color: #f5f6f5;
  position: relative;

  // padding: 0 20upx;
  .title_record_a {
    padding: 40rpx;
    background-color: #fb6802;
    border-radius: 10rpx;
    box-sizing: border-box;
    margin-bottom: 20rpx;
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin: 20rpx;

    .title_record_b {
      flex-direction: column;
      display: flex;
    }

    .title_line {
      width: 1px;
      height: 160rpx;
      background-color: #eee;
    }

    .order_nav {
      display: flex;
      flex-direction: column;
      margin-bottom: 16rpx;

      &.center {
      }

      .name {
        color: #eee;
        font-size: 24rpx;
        margin-bottom: 10rpx;
      }

      .val {
        font-size: 46rpx;
        color: #fff;

        .text {
          font-size: 28rpx;
        }
      }
    }
  }

  .data-overview {
    // height: 210px;
    display: flex;
    flex-direction: column;
    margin: 20rpx;
    background: #fff;
    border-radius: 20rpx;

    .title {
      flex: 1;
      padding: 20px;
      border-bottom: 1px solid #eee;

      text {
        color: #000;
        font-size: 32rpx;
        font-weight: 500;
        position: relative;
      }

      text::after {
        content: '';
        display: block;
        position: absolute;
        height: 20px;
        width: 2px;
        top: 2px;
        left: -10px;
        background-color: #fd243c;
      }
    }
    .height_375 {
      height: 350rpx !important;
    }
    .data-box {
      height: 450rpx;
      position: relative;

      .data-img {
        position: absolute;
        top: 0px;
        left: 0px;
        width: 100%;
        height: 450rpx;
      }

      .data-body {
        width: 88%;
        position: absolute;
        top: 0px;
        left: 0px;
        margin: 6%;

        .data-item-bootn {
          width: 100%;
          display: flex;
          flex-direction: row;
          flex-wrap: wrap;
          justify-content: space-between;
          align-items: center;
          height: 200rpx;
          .flex_item {
            flex-basis: 33%;
            margin-bottom: 20rpx;
          }
        }
      }
    }
  }
}

.dateBox {
  width: 100%;
}

.imgSty {
  width: 100%;
  height: 12px;
  transform: rotate(90deg);
  margin-right: 5upx;
}

.summary-container {
  /* height: 300upx; */
  border-radius: 20upx;
  background-image: linear-gradient(to top right, #035d85, #1c8ad0);
  padding: 20upx;
  display: flex;
  flex-direction: column;
}

.br {
  border-right: 2upx solid #ccc;
}

.title-text {
  color: #d7d7d7;
}

.charts-box {
  margin-top: 20rpx;
  border-radius: 20rpx;
  background-color: #fff;
  padding-top: 15px;
  padding-bottom: 5px;
  margin: 20rpx;

  &.hiddle {
    transform: translateX(200%);
  }

  .shouru {
    position: relative;
    left: 15px;
    font-weight: bold;
    margin-bottom: 40rpx;
    margin-left: 20rpx;
    color: #333;

    .charts_jiaoyi {
      width: 400rpx;
      height: 400rpx;
    }
  }

  .shouru::before {
    position: absolute;
    top: 50%;
    transform: translateY(-50%);
    left: -15px;
    content: '';
    display: block;
    width: 2px;
    height: 16px;
    background-color: #ff4445;
  }

  .right_charts {
    display: flex;
    align-items: center;

    .quin_data {
      width: 280rpx;
      height: 280rpx;
    }

    .title_list {
      display: flex;
      flex-direction: row;
      flex-wrap: wrap;
      padding: 0rpx 10rpx 0rpx 50rpx;

      .vard_item {
        width: 215rpx;
        display: flex;
        flex-direction: column;
        margin-bottom: 24rpx;
      }

      .paycount {
        height: 45rpx;
        line-height: 45rpx;
        display: flex;
        flex-direction: row;
        flex-wrap: nowrap;
        margin: 5rpx 0rpx;
      }

      .name {
        font-size: 24rpx;
        color: #9195ab;
        margin-bottom: 8rpx;
      }
    }
  }
}
</style>
